package org.test.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.test.web.common.R;
import org.test.web.entity.User;
import org.test.web.service.UserService;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    public R<User> hello(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,"17349656297");
        User one = userService.getOne(queryWrapper);
        return R.success(one);
    }

    /**
     * 查询
     * @param user
     * @return
     */
    @PostMapping("/getUserById")
    public R<User> getUserById(@RequestBody User user){//json数据形式接收和发送
        log.info("name-{}",user.getName());
        if(user.getPhone()!=null){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,user.getPhone());
            User one = userService.getOne(queryWrapper);
            return R.success(one);
        }
        return null;
    }

    /**
     * 更新
     * @param user
     * @return
     */
    @PostMapping("/updateUserByPhone")
    public R<String> updateUser(@RequestBody User user){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,user.getPhone());
        User one = userService.getOne(queryWrapper);

        if(user.getName()!=null && user.getSex()!=null){
            one.setSex(user.getSex());
            one.setName(user.getName());
            userService.updateById(one);
        }



        return R.success("修改user成功");
    }

    /**
     * 增加
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public R<String> addUser(@RequestBody User user){
        if(user.getPhone()!=null) {
            userService.save(user);
            return R.success("添加user成功");
        }else {
            return R.error("添加失败，或者数据有误");
        }

    }

    @PostMapping("/delUser")
    public R<String> delUser(@RequestBody User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,user.getPhone());
        queryWrapper.eq(User::getStatus,0);
        userService.remove(queryWrapper);
        return R.success("删除user成功");
    }
}
